package com.app.twth.net;


import android.util.Log;

import com.app.twth.app.Constant;
import com.app.twth.app.MyApplication;
import com.app.twth.bean.BaseResponseEntity;
import com.app.twth.ui.mine.version.UpdateVersion;
import com.app.twth.utils.FastJsonUtil;
import com.app.twth.utils.PreferencesUtil;
import com.app.twth.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.request.base.Request;
import com.tencent.bugly.crashreport.BuglyLog;
import com.tencent.bugly.crashreport.CrashReport;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Response;
import okhttp3.ResponseBody;


public abstract class JsonCallBack<T> extends AbsCallback<T> {
    private String TAG = "JsonCallBack";
    private Type type;
    private Class<T> clazz;

    public JsonCallBack() {
    }


    @Override
    public void onSuccess(com.lzy.okgo.model.Response<T> response) {
        if (response.body() instanceof BaseResponseEntity) {
            if (response.code() == 401) {
                EventBus.getDefault().post("logout");
                return;
            } else {
                BaseResponseEntity baseResponse = (BaseResponseEntity) response.body();
                if (baseResponse.getMessage() != null) {
                    if (baseResponse.getMessage().contains("login")) {
                        EventBus.getDefault().post("logout");
                        return;
                    }
                    if (baseResponse.getMessage().contains("invalid token")) {
                        EventBus.getDefault().post("logout");
                        return;
                    }
                }
            }
        }
        onSuccessData(response);
    }

    public abstract void onSuccessData(com.lzy.okgo.model.Response<T> response);

    @Override
    public T convertResponse(Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body == null) return null;
        Gson gson = new Gson();
        JsonReader reader = new JsonReader(body.charStream());
        Type genType = getClass().getGenericSuperclass();
        Type type = ((ParameterizedType) genType).getActualTypeArguments()[0];
        T data = gson.fromJson(reader, type);
        response.close();
        return data;
    }

    @Override
    public void onError(com.lzy.okgo.model.Response<T> response) {
        super.onError(response);
        try {

            Response rawResponse = response.getRawResponse();
            if (rawResponse == null) {
                onError("Network Error, Please Try Again Later");
                return;
            }
            String string = rawResponse.body().string();
//            Log.e(TAG, " body.string():" + string);
            BuglyLog.d(TAG, " body.string():" + string);
            if (!string.contains("<head><title>")) {
                BaseResponseEntity<Object> baseResponse = FastJsonUtil.getObject(string, BaseResponseEntity.class);
                if (baseResponse == null) {
                    onError("Network Error, Please Try Again Later");
                    return;
                }
                Log.e(TAG, " text:" + baseResponse.getCode());
                if (!Utils.isEmpty(baseResponse.getCode())) {
                    if (baseResponse.getCode().equals("10011")) {
                        EventBus.getDefault().post(new UpdateVersion());
                    }
                }
                onError(baseResponse.getMessage());
            } else {
                onError("Network Error, Please Try Again Later");
            }
            CrashReport.postCatchedException(response.getException());  // bugly会将这个throwable上报
        } catch (Exception e) {
            onError("Network Error, Please Try Again Later");
        }
    }

    public abstract void onError(String error);

    String url;

    @Override
    public void onStart(Request<T, ? extends Request> request) {
        super.onStart(request);

        try {
            url = request.getUrl();
//            Log.e(TAG,"url:"+ url);
//            request.headers("User-Agent", "Android");
//            request.headers("Accept-Language", "en-US;q=0.8,en;q=0.7");
//            request.headers("lang", "en");

            if (Utils.isEmpty(MyApplication.token)) {
                MyApplication.token = PreferencesUtil.getString(MyApplication.getAppInstance(), Constant.token);
            }
            if (!Utils.isEmpty(MyApplication.token)) {
                request.headers("Access-Token", "" + MyApplication.token);
            }

            if (Utils.isEmpty(MyApplication.location)) {
                MyApplication.location = PreferencesUtil.getString(MyApplication.getAppInstance(), Constant.location);
            }
            request.headers("Current-Warehouse-Id", "" + MyApplication.location);

            try {
                if (Utils.isEmpty(MyApplication.versionCode)) {
                    MyApplication.versionCode = Utils.getVersionName(MyApplication.getAppInstance());
                    request.headers("App-Version", MyApplication.versionCode);
                } else {
                    request.headers("App-Version", MyApplication.versionCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFinish() {
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public Class<T> getClazz() {
        return clazz;
    }

    public void setClazz(Class<T> clazz) {
        this.clazz = clazz;
    }

}
